package com.tanhua.server.service;

import cn.hutool.core.util.RandomUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.mongo.UserReceviveSound;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserReceviveSoundApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class PeachBlossomService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private SoundApi soundApi;

    @Reference
    private UserReceviveSoundApi userReceviveSoundApi;

    //【实战】上传音频文件业务
    public ResponseEntity<Object> upload(MultipartFile soundFile) throws IOException {
        try {
            String soundFilename = soundFile.getOriginalFilename();
            String ext = soundFilename.substring(soundFilename.lastIndexOf(".") + 1);
            StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), ext, null);
            String soundUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

            Sound sound = new Sound();
            //sound.setSid()   动态id sid在impl中添加，
            sound.setCreated(System.currentTimeMillis());
            sound.setSoundUrl(soundUrl);
            sound.setUserId(UserHolder.getUserId());

            soundApi.save(sound);
        } catch (IOException e) {
            return ResponseEntity.ok("上传失败，请重新录制");
        }

        return ResponseEntity.ok(null);

    }

    //【实战】获取音频业务
    public ResponseEntity<Object> get() {
        //获取用户名，通过用户名查询表，判断remainingTimes是否为0，为0则不再继续
        User user = UserHolder.get();
        UserReceviveSound urs = userReceviveSoundApi.findByUid(user.getId());
        if (urs.getRemainingTimes() == 0){
            return ResponseEntity.ok("您今天的传音次数用完了~");
        }

        //查询当前用户的音频，并记录id
        List<Sound> list = soundApi.findByUserId(user.getId());

        //获取sid的数组或集合,在Api中获取state为false的数据
        List<Sound> soundList = soundApi.findAll();

        //遍历sids集合，通过Random获取一个索引，查询Sound，如果Sound的state属性为false且userId不为当前用户，则返回，否则继续随机
        soundList.removeAll(list);
        int randomIndex = RandomUtil.randomInt(soundList.size());
        Sound sound = soundList.get(randomIndex);

        //获取Sound的url和userId
        String soundUrl = sound.getSoundUrl();
        Long targetUid = sound.getUserId();

        //通过音频的userId查询UserInfo
        UserInfo userInfo = userInfoApi.findById(targetUid);

        //封装数据
        SoundVo soundVo = new SoundVo();
        soundVo.setId(targetUid.intValue());
        soundVo.setAvatar(userInfo.getAvatar());
        soundVo.setNickname(userInfo.getNickname());
        soundVo.setGender(userInfo.getGender());
        soundVo.setAge(userInfo.getAge());
        soundVo.setSoundUrl(soundUrl);
        //设置remainingTimes -= 1，同时设置相应的sound的state为true
        Integer remaining = userReceviveSoundApi.reduceRemaining(user.getId());
        soundApi.updateState(sound);
        soundVo.setRemainingTimes(remaining);

        //返回数据
        return ResponseEntity.ok(soundVo);
    }

}
